<template>
  <div class="modifyPhone">
    <van-cell-group style="padding-right:16px;">
      <van-field placeholder="请输入手机号" v-model.trim="phone" type="tel" label="手机号" label-width="60"></van-field>
      <van-field v-model.trim="smsCode" maxlength="6" type="number" clearable placeholder="请输入验证码">
        <template #button>
          <SmsBtn color="#FE9100" plain size="small" :border="false" :phone="phone" />
        </template>
      </van-field>
    </van-cell-group>
    <van-button color="#FE9100" block class="submit-btn" @click="submit">保存</van-button>
  </div>
</template>

<script>
import { Button, Field, Toast, CellGroup } from 'vant';
import SmsBtn from '@components/smsBtn';
import { user_updateUserPhone } from '@api/user';

export default {
  components: {
    [CellGroup.name]: CellGroup,
    [Field.name]: Field,
    [Button.name]: Button,
    SmsBtn
  },
  data() {
    return {
      phone: '',
      smsCode: ''
    };
  },
  mounted() {
    this.phone = this.userInfo.phone;
  },
  methods: {
    async submit() {
      const { phone, smsCode } = this;
      if (!/^1[3456789]\d{9}$/.test(phone)) {
        return Toast('请输入正确的手机号');
      }
      let res = await user_updateUserPhone({ phone, smsCode });
      if (res.code === 200) {
        this.$store.commit('setUserInfo', Object.assign(this.userInfo, { phone }));
        this.$router.go(-1);
      } else {
        Toast(res.msg);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.modifyPhone {
  padding-top: 20px;
}
.submit-btn {
  margin: 70px auto 0;
  width: calc(100% - 64px);
  border-radius: 6px;
  font-size: 30px;
  font-weight: bold;
}
</style>
